package services

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	utils "hft/Http/Utils"
	"hft/global"
)

type Api struct{}

func (*Api) GetApis(id int, paginate *utils.Page) (page *utils.Page, err error) {

	var apiList = make([]*admin.Api, 0)

	global.OC_DB.Where("route_id = ?", id).Scopes(utils.Paginate(*paginate, global.OC_DB)).Find(&apiList).Scopes(dao.GetCount(global.OC_DB)).Count(&paginate.Total)

	paginate.Data = apiList

	return paginate, nil

}

func (*Api) Create(data *admin.Api) (err error) {

	res := global.OC_DB.Where("api_path = ? AND route_id = ? AND api_name = ?", data.ApiPath, data.RouteID, data.ApiName).FirstOrCreate(&data)

	if res.Error != nil {
		return res.Error
	}

	if res.RowsAffected == 0 {
		return errors.New("该资源已存在")
	}

	// 添加到超级管理员
	var role *admin.Role
	global.OC_DB.Where("id = ?", 1).First(&role)

	global.OC_DB.Model(&role).Association("Apis").Append(data)

	return nil

}

func (*Api) Edit(data *admin.Api) (err error) {
	global.OC_DB.Model(&admin.Api{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"api_name":  data.ApiName,
		"api_path":  data.ApiPath,
		"api_type":  data.ApiType,
		"is_logger": data.IsLogger,
		"is_all":    data.IsAll,
	})

	global.OC_REDIS.Set(fmt.Sprintf("api__%v", data.ApiPath), data.IsLogger, -1)

	return nil
}

func (*Api) Delete(ids []int) (err error) {

	global.OC_DB.Unscoped().Delete(&admin.Api{}, ids)

	return nil

}

var ApiService = new(Api)
